#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
//#include "type.h"
//#include "devman.h"
//#include "platform.h"
//#include "romfs.h"
//#include "xmodem.h"
#include "shell.h"
//#include "lua.h"
#include "stm32f10x.h"

extern const char romfs[];
int lua_main (int argc, char **argv);

void USART1_Init(void)
{
  GPIO_InitTypeDef 		GPIO_InitStructure;
  USART_InitTypeDef 	USART_InitStructure;  

  /* Enable GPIO clock */
  RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA | RCC_APB2Periph_AFIO | RCC_APB2Periph_USART1, ENABLE);

  GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_PP;
  GPIO_InitStructure.GPIO_Pin = GPIO_Pin_9;
  GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;	  
  GPIO_Init(GPIOA, &GPIO_InitStructure);

  /* Configure USART Rx as input floating */
  GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IN_FLOATING;
  GPIO_InitStructure.GPIO_Pin = GPIO_Pin_10;
  GPIO_Init(GPIOA, &GPIO_InitStructure);

  /* USARTx configured as follow:
        - BaudRate = 115200 baud  
        - Word Length = 8 Bits
        - One Stop Bit
        - No parity
        - Hardware flow control disabled (RTS and CTS signals)
        - Receive and transmit enabled
  */
  USART_InitStructure.USART_BaudRate = 115200;
  USART_InitStructure.USART_WordLength = USART_WordLength_8b;
  USART_InitStructure.USART_StopBits = USART_StopBits_1;
  USART_InitStructure.USART_Parity = USART_Parity_No;
  USART_InitStructure.USART_HardwareFlowControl = USART_HardwareFlowControl_None;
  USART_InitStructure.USART_Mode = USART_Mode_Rx | USART_Mode_Tx;

  USART_Init(USART1, &USART_InitStructure);
  USART_Cmd(USART1, ENABLE);
}

int main( void )
{
  FILE* fp;
//  char* lua_argv[] = { "lua", "/rom/autorun.lua", NULL };
  char* lua_argv[] = { "lua", "-e\0", (char *)romfs, "-i\0", NULL};

  USART1_Init();
  // Initialize platform first
/*  if( platform_init() != PLATFORM_OK )
  {
    // This should never happen
    while( 1 );
  }
 
  // Initialize device manager
  dm_init();
  
  // Register the ROM filesystem
  dm_register( romfs_init() );  

#ifdef BUILD_XMODEM  
  // Initialize XMODEM
  xmodem_init( xmodem_send, xmodem_recv );    
#endif
*/
#ifdef BUILD_TERM  
  // Initialize terminal
  term_init( TERM_LINES, TERM_COLS, term_out, term_in, term_translate );
#endif

  // Autorun: if "autorun.lua" is found in the ROM file system, run it first
//  if( ( fp = fopen( lua_argv[1], "r" ) ) != NULL )
  if( ( fp = fopen( lua_argv[1], "r" ) ) == NULL )
  {
    fclose( fp );
    lua_main( 2, lua_argv );    
  }
  
  // Run the shell
  if( shell_init() == 0 )
  {
    printf( "Unable to initialize the Lua shell!\n" );
    // Start Lua directly
	lua_argv[1] = NULL; 
    lua_main( 1, lua_argv );
  }
  else shell_start();

  exit(EXIT_SUCCESS);
}
